package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api("菜品相关接口")
@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishService dishService;
    @ApiOperation("新增菜品")
    @PostMapping()
    public Result addDish(@RequestBody DishDTO dishDto) {
        log.info("addDish : {}", dishDto);
        dishService.saveWithFlavor(dishDto);
        String key="dish_"+dishDto.getCategoryId();
        cleanCache(key);
        return Result.success();
    }
    @ApiOperation("菜品分页查询")
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("pageDish : {}", dishPageQueryDTO);
        PageResult result= dishService.pageQuery(dishPageQueryDTO);
        return Result.success(result);
    }

    @ApiOperation("菜品删除")
    @DeleteMapping
    public Result deleteDish(@RequestParam List<Long> ids) {//必须加注解，由spring mvc自动处理
        log.info("deleteDish : {}", ids);
        dishService.deleteBatch(ids);

        //将所有菜品缓存数据删除掉
        cleanCache("dish_*");
        return Result.success();
    }

    @ApiOperation("根据id查询菜品")
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id) {
        log.info("getDish : {}", id);
        DishVO dishVO= dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }
    @ApiOperation("修改菜品")
    @PutMapping
    public Result updateDish(@RequestBody DishDTO dishDto) {
        log.info("updateDish : {}", dishDto);
        dishService.updateWithFlavor(dishDto);
        //将所有菜品缓存数据删除掉
        cleanCache("dish_*");
        return Result.success();
    }
    @ApiOperation("菜品起售停售")
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status,Long id) {
        log.info("startOrStop : {}", id);
        dishService.startOrStop(status,id);
        cleanCache("dish_*");
        return Result.success();
    }
    @GetMapping("/list")
    public Result<List<DishVO>> list(Integer categoryId) {
        log.info("listDish");
        List<DishVO> result= dishService.getByCategoryId(categoryId);
        return Result.success(result);
    }
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
